package edu.dublbo.commons.util;

import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Slf4j
public class IpUtil {

    /**
     * 获取远程客户端的 ip
     *
     * @param request 远程客户端请求
     * @return 客户端 IP 地址
     */
    public static String getIpAddress(HttpServletRequest request) {

        String ipAddress;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    ipAddress = getSelfIpAddress();
                }
            }
            // 对于通过多个代理的情况，第一个 IP 为客户端真实 IP ,多个IP按照 ',' 分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        // ipAddress = this.getRequest().getRemoteAddr();
        return ipAddress;
    }

    /**
     * 获取本机的实际 IP 地址
     *
     * @return 本机 IP 地址
     */
    public static String getSelfIpAddress() {
        String ip = "127.0.0.1";
        try {
            // 根据网卡取本机配置的 IP
            InetAddress inet = InetAddress.getLocalHost();
            ip = inet.getHostAddress();
        } catch (UnknownHostException e) {
            log.error("获取本机的 ip 失败 ===> 网卡异常！");
            e.printStackTrace();
        }
        return ip;
    }
}
